<script setup>
// 新增表单引用
import router from "../../../router";
import {ElMessage} from "element-plus";
import request from "../../../utils/canteen";
import {onMounted, reactive, ref} from "vue";
onMounted(()=>{
  initInfo();
})
const userInfo=reactive({})
const initInfo=()=>{
  const loginUser = sessionStorage.getItem("loginUser");
  if (loginUser) {
    const userobj = JSON.parse(loginUser)
    userInfo.mname=userobj.mname;
    formAdd.identity=userInfo.mname;
  }
}
const formAddRules={
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]+$/, message: '只能输入汉字', trigger: 'blur' },
    { max: 30, message: '长度不能超过30个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
};
const formAddRef = ref()
// 新增表单初始化数据
const formAddData = {
  title:'',
  content:'',
  identity:'',
  type:2,
}
// 新增表单绑定数据模型
const formAdd = reactive({...formAddData})   // ...formAddData 解构formAddData

const onSubmitHandler = () => {
  // 数据提交到服务器
  // 服务器端返回成功 ：清空表单，关闭对话框，更新表格内容
  request({
    method:'post',
    url:'/notice/add',
    params:formAdd
  }).then(req=>{
    if (200==req.data.errorCode){
      Object.assign(formAdd , formAddData)
      ElMessage({
        type:'warning',
        message:'已交由管理员审核，请耐心等待。。。'
      })
      router.push("/home/mall/notice")
    }
  })

}
const onResetHandler = () => {
  // 清空表单数据
  Object.assign(formAdd , formAddData)
}
</script>

<template>
  <div style="text-align: center">
    <h3>发布公告</h3>
    <div class="container">
      <el-form ref="formAddRef" :model="formAdd" label-width="120px" :rules="formAddRules">
        <div class="content">
          <el-form-item prop="title" label="标题" class="custom-form-item">
            <el-input v-model="formAdd.title" type="textarea" maxlength="30" show-word-limit class="custom-input"></el-input>
          </el-form-item>
          <el-form-item prop="content" label="内容" class="custom-form-item">
            <el-input v-model="formAdd.content" type="textarea" :rows="6" placeholder="请输入公告内容" class="custom-input"></el-input>
          </el-form-item>
        </div>
        <div class="btn">
          <el-form-item>
            <el-button type="primary" @click="onSubmitHandler">添加</el-button>
            <el-button  @click="onResetHandler">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.custom-form-item {
  margin-bottom: 20px; /* 调整表单项之间的间距 */
}

.custom-input {
  width: 300px; /* 自定义输入框的宽度 */
}
.content{
  width: 600px;
  margin: 50px auto;
}
.btn{
  width: 600px;
  margin: 10px auto;
}
</style>